package net.butfly.bus.server.deploy;

import javax.servlet.ServletException;

import net.butfly.bus.EntryPoint;
import net.butfly.bus.context.Constants;
import net.butfly.bus.server.ServerConfig;
import net.butfly.bus.server.impl.EntryPointImpl;
import net.butfly.bus.util.EnumFactory;
import net.butfly.bus.util.LogUtils;

import com.caucho.hessian.io.AbstractSerializerFactory;
import com.caucho.hessian.io.SerializerFactory;
import com.caucho.hessian.server.HessianServlet;

public class HessianEntryPointServlet extends HessianServlet {

	private static final long serialVersionUID = -2493158151789223720L;
	private static LogUtils logger = LogUtils.getLog();
	private SerializerFactory factory = null;

	@Override
	public void init() throws ServletException {
		try {
			logger.info("Bus starting....");
			try {
				// set the default entry point interface and implementation.
				this.setAPIClass(EntryPoint.class);
				this.setService(new EntryPointImpl());
				super.init();
				ServerConfig.init();
				logger.info("Bus starting finished.");
			} catch (Throwable ex) {
				logger.error("Bus starting failed: ", ex.getCause());
				throw ex;
			}
		} catch (Throwable e) {
			throw new ServletException(e);
		}
	}

	public SerializerFactory getSerializerFactory() {
		if (null == factory) {
			factory = super.getSerializerFactory();
			AbstractSerializerFactory af = null;
			try {
				af = (AbstractSerializerFactory) Thread.currentThread().getContextClassLoader()
						.loadClass(Constants.EXT_EBASE_ENUMFACTORY).newInstance();
			} catch (Exception ex) {
				af = new EnumFactory();
			}
			factory.addFactory(af);
		}
		return factory;
	}
}
